package utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;

import com.ygk.bluepath.R;
import com.ygk.bluepath.core.BActivity;
import com.ygk.bluepath.core.BApp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import utils.ui.view.DialogWithOutView;

/**
 * Created by Handreace on 16-7-14.
 */
public class ImageUtil {


    /*选择图片弹框,在activity的onresult()方法拿到图像*/

    public static void showChooseDialog(final BActivity activity) {
        final DialogWithOutView dlwv = new DialogWithOutView(activity, R.style.CustomDialog);
        View view = dlwv.inflaterView(R.layout.item_popupwindows, null);

        view.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fade_ins));
        LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
        ll_popup.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.push_bottom_in_2));

        view.findViewById(R.id.item_popupwindows_camera).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlwv.dismiss();
                if (PhoneInformationUtil.hasSdCard()) {
                    takePicWithCamera(activity);
                } else {
                    activity.tt("未检测到存储卡");
                }
            }
        });
        view.findViewById(R.id.item_popupwindows_Photo).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlwv.dismiss();
                if (PhoneInformationUtil.hasSdCard()) {
                    selectImageFromAlbums(activity);
                } else {
                    activity.tt("未检测到存储卡");
                }
            }
        });
        view.findViewById(R.id.item_popupwindows_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlwv.dismiss();
            }
        });
        dlwv.setCanceledOnTouchOutside(true);
        dlwv.setWindowAnimations(R.style.dialogWindowAnim_up); // 设置窗口弹出动画
        dlwv.setBgTransparent();
        dlwv.setGravityBottom();

        dlwv.show();
    }


    /*从摄像头获取图片*/

    public static void takePicWithCamera(BActivity activity) {

        File file = new File(Inf.cameraPath);
        if (file.exists()) {
            file.delete();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                LogUtils.e("文件创建失败");
                return;
            }
        }

        Uri imageUri = Uri.fromFile(file);

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        activity.startActivityForResult(openCameraIntent, Inf.TAKE_PICTURE_CAMERA);

    }

    /*从手机相册获取图片*/

    public static void selectImageFromAlbums(BActivity activity) {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
        }
        activity.startActivityForResult(intent, Inf.TAKE_PICTURE_ALBUMS);
    }


    public static void savePicfileWithMaxSize(String sourcePath, String filename, String path, int sizeMax) {
        //sizeMax:保存图片大小的最大伐值

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream out = null;
        Bitmap bitmap = null;
        try {
            File file = new File(path, filename);
            // 若存在即删除-默认只保留一张
            if (file.exists()) {
                file.delete();
            }
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            // 保存到储存
            out = new FileOutputStream(file);
            bitmap = getImageThumbnail(sourcePath, 720, 1280);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            int len = baos.toByteArray().length;
            /*
			 * File filesource = new File(sourcePath); long
			 * fileLen=filesource.length();
			 */
            LogUtils.e("soure-W-" + bitmap.getWidth() + "-H-"
                    + bitmap.getHeight());

            int max = sizeMax * 1024;

            if (len <= max) {
                LogUtils.e("manzu");
                out.write(baos.toByteArray());
                out.flush();

            } else {
                int q = 100;
                while (len > max) {
                    baos.reset();
                    if (q <= 20) {
                        q = 10;
                    } else {
                        q -= 20;
                    }

                    bitmap.compress(Bitmap.CompressFormat.JPEG, q, baos);
                    LogUtils.e(q + "--file.length():" + len);
                    if (q <= 10) {
                        break;
                    }
                    len = baos.toByteArray().length;
                }
                out.write(baos.toByteArray());
                out.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (out != null) {
                try {
                    if (bitmap != null) {
                        recycle(bitmap);
                    }
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static void saveBitmapWithMaxSize(Bitmap sourceBm, String filename,String path, int sizeMax) {
        //sizeMax:保存图片大小的最大伐值

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(path, filename);
        // 若存在即删除-默认只保留一张

        if (file.exists()) {
            file.delete();
        }

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // float i = 1;
        float q = 1;

        FileOutputStream out = null;
        try {
            file = new File(path, filename);
            // 保存到储存
            out = new FileOutputStream(file);
            if (sourceBm.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
            }
            long fileLen = file.length();
            LogUtils.e(sourceBm.getWidth() + "w--h" + sourceBm.getHeight()
                    + "----file.length(1)" + fileLen);
            if (fileLen <= (sizeMax * 1024)) {
                LogUtils.e("manzu::" + sizeMax * 1024);
                return;
            }
            while (fileLen > (sizeMax * 1024)) {

                if (file.exists()) {
                    file.delete();
                }

                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                out = new FileOutputStream(file);
                q *= 0.8;
                if (sourceBm.compress(Bitmap.CompressFormat.JPEG,
                        (int) (100 * q), out)) {
                    out.flush();
                }
                fileLen = file.length();
                LogUtils.e(((int) (q * 100)) + "---" + q + "--file.length():"
                        + fileLen);
                if (((int) (q * 100)) <= 1) {
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static Bitmap getImageThumbnail(Bitmap bm, int needWidth, int needHeight) {
        Bitmap bitmap = null;

        // 计算缩放比
        int bmH = bm.getHeight();
        int bmW = bm.getWidth();
        // 计算宽高缩放率
        float beWidth = ((float) needWidth) / bmW;
        float beHeight = ((float) needHeight) / bmH;
        float be = 1;
        if (bmW < bmH) {
            be = beHeight;
        } else {
            be = beWidth;
        }
        if (be > 1) {
            be = 1;
        }
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();

        // 缩放图片动作
        matrix.postScale(be, be);
        bitmap = Bitmap.createBitmap(bm, 0, 0, bmW, bmH, matrix, true);
        return bitmap;
    }

    /**
     * 获取指定路径下的图片的指定大小的缩略图 getImageThumbnail
     *
     * @return Bitmap
     * @throws
     */
    public static Bitmap getImageThumbnail(String imagePath, int needWidth, int needHeight) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        // 计算缩放比
        int bmH = options.outHeight;
        int bmW = options.outWidth;

        if (bmW < bmH) {
            int ca = needWidth;
            needWidth = needHeight;
            needHeight = ca;
        }

        int be = 1;
        if ((bmW > needWidth) && (bmH > needHeight)) {
            float bew = 1;
            float beh = 1;
            bew = ((float) bmW) / ((float) needWidth);
            beh = ((float) bmH) / ((float) needHeight);

            if (bew > beh) {
                be = (int) bew;
            } else {
                be = (int) beh;
            }
        } else if (bmW > needWidth) {
            be = bmW / needWidth;
        } else if (bmH > needHeight) {
            be = bmH / needHeight;
        }

        LogUtils.e(be + "-soure-w-" + bmW + "-H-" + bmH);

        if (be < 1) {
            be = 1;
        }

        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        options.inJustDecodeBounds = false; // 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		/*
		 * bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
		 * ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		 */
        return bitmap;
    }

    /**
     * 回收垃圾 recycle
     *
     * @throws
     */
    public static void recycle(Bitmap bitmap) {
        // 先判断是否已经回收
        if (bitmap != null && !bitmap.isRecycled()) {
            // 回收并且置为null
            bitmap.recycle();
            bitmap = null;
        }
        System.gc();
    }

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
